'use strict';

/**
 * 代理
 */
var Router = require('koa-router');
var __pathPrefix = '/';
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();

var proxyMgr = require('../proxy_mgr.js');
var proxy = require('koa-proxy');

router.all('**', function*(next) {
  console.log('router_proxy');
  var url = this.request.url;
  var server = proxyMgr.getServer(url);
  if (!server) {
    console.log('no proxy with url:', url);
    return yield next;
  }
  var thisProxy = proxy({host: server.host});
  try {
    var proxyStartAt = new Date().getTime();
    yield thisProxy;
    var proxyTime = new Date().getTime() - proxyStartAt;
    var resultStatus = this.status < 500 ? proxyMgr.CntType.cntSucc : proxyMgr.CntType.cntFail;
    proxyMgr.reportProxyResult(server, proxyTime, resultStatus);
  } catch (e) {
    proxyMgr.reportProxyResult(server, -1, proxyMgr.CntType.cntFail);
  }

  console.log('proxy result, status=%s,body=%s', this.status, this.body);
  proxyMgr.printServerInfo(server);
  // else
  //yield next;
});
